<template>
  <el-dialog :title="title" :visible.sync="open" width="65%" append-to-body :before-close="closeDelDialog">
    <div>
      <h1 style="font-size: 28px;" class="h1" v-if="isShow == '1'">四性检测配置</h1>
      <h1 style="font-size: 28px;" class="h1" v-if="isShow == '2' || isShow == '3'">四性检测详情</h1>
      <el-button type="primary" style="float: right; margin-right: 1%; margin-bottom: 0.5%" v-if="isShow == '1'"
        @click="allOnTap">全部不检测</el-button>
      <el-button type="primary" style="float: right; margin-right: 1%; margin-bottom: 0.5%" v-if="isShow == '1'"
        @click="allYesTap">全部通过</el-button>

      <el-button type="primary" style="float: right; margin-right: 1%; margin-bottom: 0.5%" @click="handleConfigure"
        v-if="isShow == '1'">配置</el-button>
      <el-button type="primary" style="float: right; margin-right: 1%; margin-bottom: 0.5%" @click="handleSubmit"
        v-if="isShow == '3'" :disabled="isShowButton">提交归档申请</el-button>
    </div>
    <div style="width: 99%; margin: 0 auto">
      <el-table :data="tableData" border :span-method="tableSpanMethod" height="600">
        <el-table-column align="center" prop="index1" label=""></el-table-column>
        <el-table-column align="center" prop="index2" label=""></el-table-column>
        <el-table-column align="center" prop="index3" label="检测项目"></el-table-column>
        <el-table-column label="检测配置" width="350px" align="center" header-align="center" prop="configuration"
          v-if="isShow == '1'">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.configuration.isDetection == '0'"
              @change="handleDetectionChange(scope.row.configuration)">不检测</el-checkbox>
            <el-checkbox v-model="scope.row.configuration.isPass == '1'"
              @change="handlePassChange(scope.row.configuration)">默认通过</el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="检测结果" width="200px" align="center" header-align="center" prop="configuration"
          v-if="isShow == '2'">
          <template slot-scope="scope">
            <el-button type="text" v-if="scope.row.configuration.detectionResult == '1'"
              v-show="scope.row.configuration.detectionResult == '1'">通过</el-button>
            <el-button type="text" v-show="scope.row.configuration.detectionResult == '0'" v-else
              @click="handleFail(scope.row.configuration)">不通过</el-button>
          </template>
        </el-table-column>

        <el-table-column label="检测结果" width="200px" align="center" header-align="center" prop="configuration"
          v-if="isShow == '3'">
          <template slot-scope="scope">
            <span type="text" v-if="scope.row.configuration.detectionResult == '1'"
              v-show="scope.row.configuration.detectionResult == '1'">通过</span>
            <el-button type="text" v-show="scope.row.configuration.detectionResult == '0'"
              v-else-if="scope.row.configuration.detectionResult == '0' && scope.row.dId == '1224'"
              @click="handleFail(scope.row.configuration)">不通过</el-button>
            <el-button type="text" v-show="scope.row.configuration.detectionResult == '0'" v-else
              @click="handleFail(scope.row.configuration)">不通过{{ scope.row.configuration.failNum
              }}条</el-button>
          </template>
        </el-table-column>
        <el-table-column label="检测时间" width="250px" align="center" header-align="center" prop="configuration"
          v-if="isShow == '2' || isShow == '3'">
          <template slot-scope="scope">
            <span>{{ scope.row.configuration.detectionTime }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <configureDetail v-if="configureOpen" :open="configureOpen" ref="configureRef"
      @configureCancelTap="configureCancelTap"></configureDetail>

    <FailList v-if="failOpen" :open="failOpen" ref="failRef" @cancel="cancel"></FailList>
  </el-dialog>
</template>

<script>
import ConfigureDetail from "@/views/archive/fourNatures/detectionPlan/configureDetail";
import FailList from "@/views/archive/fourNatures/detectionPlan/failList";
import estimateTableHeight from "@/mixins/estimateTableHeight";
export default {
  name: "planDetail",
  components: { FailList, ConfigureDetail },
  props: ["open", "isShow", "title"],
  mixins: [estimateTableHeight], // 混入方法
  data() {
    return {
      treeData: [],
      tableData: [],
      // 外层列表行数据信息
      info: null,
      configureOpen: false,
      firstNodes: [],
      bottomNodes: [],
      configurationInfo: [],

      failOpen: false,
      isShowButton: true
    }
  },
  created() {
  },
  methods: {
    init(val, info) {
      console.log(val, info)
      this.treeData = val
      this.info = info
      this.getTableData()
    },
    getTableData() {
      let lastChildNode = this.getLastChildNode(JSON.parse(JSON.stringify(this.treeData)));
      // 需要一个有且只有一个根节点的数据（如果返回的数据有且只有一个根节点，可省略此步骤）
      let obj = {
        id: '',
        pId: '',
        label: '',
        children: this.treeData // 删除 最后一级节点
      }
      // 将 树结构数据 格式化为二维数组
      let formatArr = this.parseTreeToRow(obj);
      // console.log(formatArr)

      // 再将其格式化为一维数组(ElementUi 表格所需要的数据格式)
      let tableData = [];
      if (formatArr[0].length != 0) {
        formatArr.map((item, index) => {
          let pushObj = { number: index + 1 }; // 添加索引值（列 序号），如不需要，则设置为空对象
          item.map((itemb, indexb) => {
            // 动态添加 指标列数据 对应 表头 prop 属性值
            pushObj['index' + (indexb + 1)] = itemb.label;
            // 添加 表格行数据 id (取的是最后一个children的 id 值)
            if (indexb == item.length - 1) {
              pushObj.id = itemb.id;
            };
          });
          tableData.push(pushObj)
        });
      }
      // 

      // 获取树结构最深层级数
      this.getMaxFloorNum = this.getMaxFloor(this.treeData);

      // 未达到最深层级数节点 补充数据空缺
      for (let i = 0; i < tableData.length; i++) {
        for (let j = 0; j < this.getMaxFloorNum; j++) {
          if (tableData[i]['index' + (j + 1)] == undefined) {
            tableData[i]['index' + (j + 1)] = tableData[i]['index' + j];
          }
        }
      }
      // 将抽离的最后一级节点 插入到 一维数组
      tableData.map((item, index) => {
        item.configuration = lastChildNode[index]
      });

      this.tableData = tableData;

      console.log(this.tableData, "ceshi")
      var list = []
      var arr = []
      for (let i = 0; i < this.tableData.length; i++) {
        list.push(this.tableData[i].configuration.detectionResult)
      }
      this.isShowButton = list.includes('0')

      for (let i = 0; i < this.tableData.length; i++) {
        this.configurationInfo.push(JSON.parse(JSON.stringify(this.tableData[i].configuration)));
      }




    },

    //全部不检测
    allOnTap() {
      var that = this;
      for (var i in that.tableData) {
        that.tableData[i].configuration.isDetection = "0"; //不检测
        that.tableData[i].configuration.isPass = "0"; //不默认通过，不勾选的状态
      }

      for (var j in  that.configurationInfo) {
        that.configurationInfo[j].isDetection = "0"; //不检测
        that.configurationInfo[j].isPass = "0"; //不默认通过，不勾选的状态
      }
    },

    //全部通过
    allYesTap() {
      var that = this;
      for (var i in that.tableData) {
        that.tableData[i].configuration.isDetection = "1";
        that.tableData[i].configuration.isPass = "1";

      }

      for (var j in  that.configurationInfo) {
        that.configurationInfo[j].isDetection = "1"; //不检测
        that.configurationInfo[j].isPass = "1"; //不默认通过，不勾选的状态
      }

    },


    /**
     * 合并行或列的计算方法
     */
    tableSpanMethod({ row, column, rowIndex, columnIndex }) {
      return {
        rowspan: this.mergeRows(row[column.property], this.tableData, rowIndex, column.property),
        colspan: columnIndex > 0 ? this.mergeCells(row[column.property], row, column.property, this.getMaxFloorNum) : 1
      };
    },
    /**
     * 递归-----取出树组件最后子节点
     * @param {Object} node      树的源数据
     * @returns {Object} temp    取出树组件最后子节点的集合
     */
    getLastChildNode(node, temp = []) {
      let forFn = (arr) => {
        for (let i = 0; i < arr.length; i++) {
          if (!arr[i].children || arr[i].children.length == 0) {
            temp.push(...arr);
            arr = [];
          } else {
            forFn(arr[i].children)
          }
        }
      }
      forFn(node)
      return temp;
    },
    /**
     * 递归-----删除树组件源数据的最后子节点
     * @param {Object} node      树的源数据
     * @returns {Object} node    删除最后子节点之后的树的数据
     */
    deleteSourceNode(node) {
      for (let i = node.length - 1; i >= 0; i--) {
        if (!node[i].hasOwnProperty('children')) {
          continue;
        }
        if (!node[i].children || node[i].children.length == 0) {
          node.splice(i, 1);
          continue;
        }
        this.deleteSourceNode(node[i].children);
      }
      return node;
    },
    /**
     * 递归-----将树结构数据格式，转化为 二维数组 表格形式
     * @param node  树的源数据
     * @param data  树转化为二维数组的数据
     * @param row   临时存储数据
     * @returns {*[]}
     */
    parseTreeToRow(node, data = [], row = []) {
      if (!node.children || node.children.length == 0) {
        data.push(row);
      } else {
        node.children.map((item, index) => {
          const obj = {
            id: item.dId,
            pId: item.superId,
            label: item.dName,
            children: item.children
          };
          this.parseTreeToRow(item, data, [...row, obj]);
        });
      }
      return data;
    },
    /**
     * 递归-----树形数据（数组）获取最深层级数
     * @param {Object} treeData    树的源数据
     * @returns {Number}           最深层级数的值
     */
    getMaxFloor(treeData) {
      let floor = 0;
      let max = 0;
      let deepEach = (data, floor) => {
        data.map((item, index) => {
          item.floor = floor;
          if (floor > max) {
            max = floor;
          };
          if (item.children && item.children.length != 0) {
            deepEach(item.children, floor + 1);
          };
        });
      };
      deepEach(treeData, 1);
      return max;
    },
    /**
     * 表格单元格合并-----行
     * @param {Object} value      当前单元格的值
     * @param {Object} data       当前表格所有数据
     * @param {Object} index      当前单元格的值所在 行 索引
     * @param {Object} property   当前列的property
     * @returns {number}          待合并单元格数量
     */
    mergeRows(value, data, index, property) {
      // 判断 当前行的该列数据 与 上一行的该列数据 是否相等
      if (index !== 0 && value === data[index - 1][property]) {
        // 返回 0 使表格被跨 行 的那个单元格不会渲染
        return 0;
      };

      // 判断 当前行的该列数据 与 下一行的该列数据 是否相等
      let rowSpan = 1;
      for (let i = index + 1; i < data.length; i++) {
        if (value !== data[i][property]) {
          break;
        };
        rowSpan++;
      };
      return rowSpan;
    },
    /**
     * 表格单元格合并-----列
     * @param {Object} value      当前单元格的值
     * @param {Object} row        当前行数据
     * @param {Object} property   当前列的property
     * @param {Object} floorNum   二级指标的层级数
     * @returns {number}          待合并单元格数量
     */
    mergeCells(value, row, property, floorNum) {
      if (property != undefined) {
        // 取出当前 property 的尾数的 数字值
        let index = Number(property.substring(5));
        // 判断 当前行的该列数据 与 上一列数据 是否相等 (由于 “一级指标” 列不参与跨列，“二级指标” 列开始参与跨列，所以判断 property !== 'index2')
        if (property !== 'index2' && value === row['index' + (index - 1)]) {
          // 返回 0 使表格被跨 列 的那个单元格不会渲染
          return 0;
        }

        // 判断当前行的该列数据 与 下一列数据 是否相等
        let colSpan = 1;
        for (let i = index; i < floorNum; i++) {
          if (value !== row['index' + (index + 1)]) {
            break;
          }
          colSpan++;
        }
        return colSpan;
      } else {
        return 1;
      }
    },

    // 处理不检测/默认通过 两者只能勾选一个
    handleDetectionChange(configuration) {
      // console.log(configuration)
      if (configuration.isDetection == '0') {
        configuration.isDetection = '1';
        this.configurationInfo.find(item => item.dId == configuration.dId).isDetection = '1'
      } else {
        configuration.isDetection = '0';
        this.configurationInfo.find(item => item.dId == configuration.dId).isDetection = '0'
        configuration.isPass = '0';
        this.configurationInfo.find(item => item.dId == configuration.dId).isPass = '0'
      }
    },
    handlePassChange(configuration) {
      // console.log(configuration)
      if (configuration.isPass == '1') {
        configuration.isPass = '0';
        this.configurationInfo.find(item => item.dId == configuration.dId).isPass = '0'
      } else {
        configuration.isPass = '1';
        this.configurationInfo.find(item => item.dId == configuration.dId).isPass = '1'
        configuration.isDetection = '1';
        this.configurationInfo.find(item => item.dId == configuration.dId).isDetection = '1'
      }
    },
    // 关闭
    closeDelDialog() {
      this.$emit('planCancelTap')
    },
    // 配置
    handleConfigure() {
      console.log(this.configurationInfo)
      this.configureOpen = true
      this.$nextTick(() => {
        this.$refs.configureRef.init(this.configurationInfo, this.info)
      })
    },
    configureCancelTap(item) {
      this.configureOpen = false
      if (item == 'save') {
        this.$emit('planCancelTap')
      }
    },

    // 不通过
    handleFail(configuration) {
      console.log(configuration, this.info)
      this.failOpen = true
      this.$nextTick(() => {
        this.$refs.failRef.init(configuration.dId, this.info.id)
      })
    },
    cancel() {
      this.failOpen = false
    },

    // 提交归档审批
    handleSubmit() {
      this.$emit('handleSubmit')
    }
  }
}
</script>

<style lang="scss" scoped>.h1 {
  font-size: 28px;
  text-align: center;
}</style>
